package com.zero.manager.controller;

import cn.hutool.core.io.FileUtil;
import com.zero.manager.common.AuthAccess;
import com.zero.manager.common.Result;
import com.zero.manager.exception.ServiceException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 功能：上传文件和下载文件的请求接收
 * 作者：zero
 * 日期：2024/9/8 18:35
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${ip:localhost}")
    private String ip;

    @Value("${server.port}")
    private String port;


    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";

    //@AuthAccess
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename(); // 文件的原始名称
//        String mainName = FileUtil.mainName(originalFilename); //index
        String extName = FileUtil.extName(originalFilename); //png

        File parentFile = new File(ROOT_PATH);
        if (!parentFile.exists()) {
            parentFile.mkdirs(); //如果当前文件的父级目录不存在，就创建
        }

        originalFilename = System.currentTimeMillis() + "." + extName;
        String fileRealPath = ROOT_PATH + File.separator + originalFilename;
        File saveFile = new File(fileRealPath);

        file.transferTo(saveFile); //存储到本地磁盘
        String url = "http://" + ip + ":" + port + "/file/download/" + originalFilename;
        return Result.success(url); //返回文件的链接，这个链接就是文件的下载地址，这个下载地址就是我的后台提供的接口
    }

    @AuthAccess
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse resp) throws IOException {
        String filePath = ROOT_PATH + File.separator + fileName;
        if (!FileUtil.exist(filePath)) {
            throw new ServiceException("404", "文件不存在");
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(bytes);//数组是一个字节数组，也就是文件的字节流数组
        outputStream.flush();
        outputStream.close();
    }
}
